package com.simplesoft.accountbook;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;

public class ExportCSVTask extends AsyncTask<Void, Void, Boolean>{
	
	private Context parent;
	private BetterProgressDialog progressDlg = null;
	private final String CSV_FILE_NAME = "MoneyRecord.csv";

	public ExportCSVTask (Context parent) {
		this.parent = parent;
	}
	
	@Override
	protected Boolean doInBackground(Void... params) {
		if (checkSDCard() != 0) {			
			return false;
		}		
		File fout = new File(Environment.getExternalStorageDirectory(), this.CSV_FILE_NAME);
		MyDatabaseOpenHelper helper = new MyDatabaseOpenHelper(parent);
		SQLiteDatabase mydb = helper.getReadableDatabase();
		FileWriter fw = null;
		
		try {
			fout.createNewFile();
			fw = new FileWriter(fout);
			Cursor cr = mydb.query("money_record", null, null, null, null, null, null);
			//Write column names.
			String colNames[] = cr.getColumnNames();
			int colCount = cr.getColumnCount();
			StringBuilder sb = new StringBuilder();
			Boolean first = true;
			for (String col : colNames) {
				if (first) {
					first = false;
				} else {
					sb.append(",");
				}
				sb.append(col);
			}
			fw.write(sb.toString());
			fw.write("\n");
			//Write data
			while(cr.moveToNext()) {
				sb = new StringBuilder();
				first = true;
				for (int i = 0; i < colCount; i++) {
					if (first) {
						first = false;
					} else {
						sb.append(",");
					}
					sb.append(cr.getString(i));
				}
				fw.write(sb.toString());
				fw.write("\n");
			}
			return true;
		} catch (IOException ioe) {
			ioe.printStackTrace();
			return false;
		} finally {
			try {
				if (fw != null) {
					fw.close();
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
	}

	@Override
	protected void onPostExecute(Boolean result) {
		this.progressDlg.dismiss();
		if (result) {
			Toast.makeText(this.parent, parent.getString(R.string.str_successful_csv_export), Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this.parent, parent.getString(R.string.str_failed_csv_export), Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onPreExecute() {
		this.progressDlg = new BetterProgressDialog(this.parent);
		this.progressDlg.show();
	}

	@Override
	protected void onProgressUpdate(Void... values) {
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
	}

	private int checkSDCard () {
		String state = Environment.getExternalStorageState();
		
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return 0; //SD card is okay.
		} else if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
			return 1; //SD card is read-only.
		} else {
			return 2; //SD card is not available.
		}
	}
}
